﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Activities.Rules;
using System.Windows.Forms;

namespace RelationExpertSystem
{
    class TestRelationSession : ISession
    {
        private TestPeopleBuilder _pb;
        private RelationRulesManager _rulesManager;

        public event EventHandler<FactsEventArgs> FactsLoaded
        {
            add { _pb.FactsLoaded += value; }
            remove { _pb.FactsLoaded -= value; }
        }

        public event EventHandler<FactsEventArgs> FactsUpdated
        {
            // Updating not implemented, so just connect to initial load
            add { _pb.FactsLoaded += value; }
            remove { _pb.FactsLoaded -= value; }
        }

        public event EventHandler<MessageEventArgs> NewInference;
        private void RaiseNewInference(MessageEventArgs args)
        {
            EventHandler<MessageEventArgs> eh = NewInference;
            if (eh != null)
                eh(this, args);
        }

        public TestRelationSession(RelationRulesManager rulesManager)
        {
            _pb = new TestPeopleBuilder(); // TODO: decouple?
            _rulesManager = rulesManager;

            _rulesManager.NewRelationInferred += new EventHandler<RelationEventArgs>(HandleNewRelationInferred);
        }

        public void LoadFacts()
        {
            _pb.BuildPairs(); // TODO: Thread this
        }

        public void EditFacts()
        {
            MessageBox.Show("Cannot edit test facts", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public void NewFacts()
        {
            MessageBox.Show("Cannot start new test facts", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public void Infer()
        {
            _rulesManager.FireRules<RelationEventArgs>(_pb.GetPairs());
        }

        public void ClearInferences()
        {
            _pb.ClearInferences();
        }

        private void HandleNewRelationInferred(object sender, RelationEventArgs e)
        {
            string message = String.Format("{0} is {1}'s {2}", e.PersonB.Name, e.PersonA.Name, e.Relation.GetType().GetShortName());
            RaiseNewInference(new MessageEventArgs(message));
            //Debug.WriteLine("Inference: " + message);
        }
    }
}
